package cc.buttfu.thingbento;
//why the crap isn't this committing?
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.RedirectHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import cc.buttfu.thingbento.R;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
/**
 * @author dislink.now
 * 
 *         Login screen for authenticating user credentials and retrieving and
 *         storing a session cookie.
 * 
 */
public class LoginScreen extends Activity implements Runnable {
	private EditText username;
	private EditText password;
	private Button login;
	private String loginUrl = "http://thingbox.com/account/login";

	public void run() {

		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				login.setText("Cancel");
				username.setEnabled(false);
				password.setEnabled(false);
			}
		});

		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = null;

		HttpParams params = new BasicHttpParams();
		HttpClientParams.setRedirecting(params, false);
		client.setParams(params);
		
		HttpPost httppost = new HttpPost(loginUrl);

		try {

			/* HTTP POST key/value pairs */
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

			/* TODO: save username / password */
			nameValuePairs.add(new BasicNameValuePair("user_login", username
					.getText().toString()));
			nameValuePairs.add(new BasicNameValuePair("user_password", password
					.getText().toString()));
			nameValuePairs.add(new BasicNameValuePair("commit", "login"));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			response = client.execute(httppost);
			InputStream contentStream = response.getEntity().getContent();

			HtmlCleaner cleaner = new HtmlCleaner();
			TagNode tn = cleaner.clean(contentStream);
			final TagNode[] notices = tn.getElementsByAttValue("id", "notices",
					true, true);
			String setCookie = response.getHeaders("Set-Cookie")[0].getValue();

			/*
			 * Hopefully the session cookie will always be element 0 but who
			 * knows
			 */
			final String cookie = setCookie.split("; ")[0];

			/* UI operations must only be performed on the UI thread */
			runOnUiThread(new Runnable() {
				public void run() {

					/*
					 * If the login has failed, there will be an element here of
					 * class "warning"
					 */
					if (notices.length > 0
							&& notices[0].getAttributes().containsValue(
									"warning")) {

						/* Reset the login page */
						login.setText("Log in");
						username.setEnabled(true);
						password.setEnabled(true);

						/* TODO Why doesn't this work? */
						Toast.makeText(LoginScreen.this, "Login failed", 5);

					} else {
						SharedPreferences prefs = PreferenceManager
								.getDefaultSharedPreferences(LoginScreen.this);
						Editor editor = prefs.edit();
						editor.putString("cookie", cookie);
						editor.commit();

						/*
						 * Go "back" to the activity that initiated the login
						 * screen.
						 */
						finish();
					}

				}
			});

		} catch (Exception e) {
			e.printStackTrace();

		}

	}

	Thread loginnerThread;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loginscreen);

		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		login = (Button) findViewById(R.id.login);

		login.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				/*
				 * Run login procedure in a separate thread to avoid killing the
				 * UI
				 */
				loginnerThread = new Thread(LoginScreen.this);
				loginnerThread.start();
			}
		});

	}

}
